package com.is2.patchinglife.listener;

import com.is2.patchinglife.manager.LocalDataManager;
import com.is2.patchinglife.manager.NotificationHandler;
import com.is2.patchinglife.util.SensorValues;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

public class AccelerometerListener implements SensorEventListener{
		
		// CONSTANTS
		private	final long NORM = 1000000000; // 1s [ns]
		
		// FREQUENCY PARAMETERS
		private double lastAcquire;		// time of last acquired value
		private double minDelay = 0.5; 	//delay [s]
		
		// TROPHY PARAMETERS
		
		// flip_01
		private double startFlip = -1;			// trophy start time
		private String flipKey = "flip_01";
		private final long FLIP_TIMEOUT = 10; 	// timeout [s]
		private final int OFF = -5;				// value offset
	         
		@Override
		/** Activated when sensor accuracy changes **/
		public void onAccuracyChanged(Sensor arg0, int arg1){}
	
		@Override
		/** Activated when sensor value changes **/
		public void onSensorChanged(SensorEvent event){
			
			// update sensor value in SHARED_MEMORY
			SensorValues.setValue("accX",event.values[0]);
			SensorValues.setValue("accY",event.values[1]);
			SensorValues.setValue("accZ",event.values[2]);
			
			// slow down execution frequency
			if((lastAcquire+minDelay)<(event.timestamp/NORM)){
				lastAcquire = event.timestamp/NORM;
				
				// trophy codes
				checkFlip01(event.values[2]);
			}
		}
			
		// TROPHY: flip_01
		private void checkFlip01(float _z){
			
			if(!LocalDataManager.getGotIT(flipKey)){
				if(_z>OFF || startFlip==-1)
					startFlip=lastAcquire;
				
				if((lastAcquire-startFlip)>FLIP_TIMEOUT){
					LocalDataManager.gotNewTrophy("flip_01");
					NotificationHandler.displayNotificationMessage(LocalDataManager.getName(flipKey),LocalDataManager.getDesc(flipKey),LocalDataManager.getID(flipKey));
				}
			}
		}
		
}